﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Reflection;

namespace Common.Util
{
    public class XmlUtil
    {
        static log4net.ILog logger = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private static XmlSerializerNamespaces namespaces;

        public static string Serialize(object obj)
        {
            if (namespaces == null)
            {
                namespaces = new XmlSerializerNamespaces();
                namespaces.Add("", "");
            }
            StringWriter textWriter = new StringWriter();
            new XmlSerializer(obj.GetType()).Serialize(textWriter, obj, namespaces);
            string str = textWriter.ToString();
            textWriter.Close();
            return str;
        }

        public static void SerializeFile(object obj, string file)
        {
            if (namespaces == null)
            {
                namespaces = new XmlSerializerNamespaces();
                namespaces.Add("", "");
            }
            FileUtil.CreateFolderByFile(file);
            StreamWriter textWriter = new StreamWriter(file);
            new XmlSerializer(obj.GetType()).Serialize(textWriter, obj, namespaces);
            textWriter.Close();
        }

        public static object Deserialize(Type type, string xml)
        {
            StringReader textReader = new StringReader(xml);
            XmlSerializer serializer = new XmlSerializer(type);
            object obj2 = null;
            try
            {
                obj2 = serializer.Deserialize(textReader);
            }
            catch (Exception exception)
            {
                logger.Debug(exception);
            }
            textReader.Close();
            return obj2;
        }

        public static object DeserializeFile(Type type, string file)
        {
            StreamReader textReader = null;
            try
            {
                textReader = new StreamReader(file);
            }
            catch (Exception exception)
            {
                logger.Debug(exception);
                return null;
            }
            XmlSerializer serializer = new XmlSerializer(type);
            object obj2 = null;
            try
            {
                obj2 = serializer.Deserialize(textReader);
            }
            catch (Exception exception2)
            {
                logger.Debug(exception2);
            }
            textReader.Close();
            return obj2;
        }
    }
}
